// components/book/bookDetail/bookDetail.js
const app = getApp()
Page({
  data: {
    book: {},
    // 当前的操作状态
    operate: '',
    comments: [],
    label: '',
    curTab: 'info',
    isOwn: false,
    // 控制输入组件
    isInputting: false,
    // 判断登录状态
    isLogin: false
  },

  onLoad () {
    this.loadData()
  },
  loadData () {
    // 接收子组件传值
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('accepData', async (data) => {
      const book = data.data
      const operate = data.operate
      const comments = data.data.comments
      let label = ''
      data.types.forEach(item => {
        if (item.typeId === book.type) {
          label = item.label
        }
      })

      this.setData({
        book,
        operate,
        comments,
        label
      })
    })
    if (app.globalData.userInfo && app.globalData.userInfo.books) {
      this.setData({
        isLogin: true
      })
      app.globalData.userInfo.books.forEach(item => {
        if (item.bookId === this.data.book.bookId) {
          this.setData({
            isOwn: true
          })
        }
      })
    } else {
      this.setData({
        isOwn: false
      })
    }
  },
  // 判断登录状态
  async goLogin() {
    if (!this.data.isLogin) {
      const { confirm } = await wx.showModal({
        title: '提示',
        content: '请先登录再操作！'
      })
      if (confirm) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
        const waitLogin = () => new Promise((resolve, reject) => {
          const timer = setInterval(() => {
            if (app.globalData.userInfo) {
              clearInterval(timer)
              resolve()
            }
          }, 20)
        }).then(res => {
          this.setData({
            isLogin: true
          })
          this.loadData()
        })
        await waitLogin()
      }
    }
  },
  // 切换 tab 
  handleChangeTab (e) {
    const curTab = e.currentTarget.dataset.tab
    this.setData({
      curTab
    })
    if (this.data.curTab === 'comment') {
      this.loadComments()
    }
  },
  // 重新加载评论
  async loadComments(noToast) {
    if (!noToast) {
      wx.showLoading({
        title: '评论加载中...'
      })
    }
    const commentsData = await wx.cloud.callFunction({
      name: 'loadBookComments',
      data: { comments: this.data.comments }
    })
    commentsData.result.forEach(item => {
      item.createdTime = new Date(item.createdTime).toLocaleString()
    })
    this.setData({
      comments: commentsData.result
    })
    if (!noToast) {
      wx.hideLoading()
    }
  },
  // 借阅功能
  async handleBorrow (e) {
    await this.goLogin()
    if (!app.globalData.userInfo) {
      return
    } else {
      wx.showLoading({
        title: '请稍候...',
        mask: true
      })
      const { result } = await wx.cloud.callFunction({
        name: 'borrowBook',
        data: this.data.book
      })
      if (result.status === 0) {
        wx.showToast({
          title: result.msg,
          icon: 'success'
        })
        this.setData({
          isOwn: true
        })
        app.globalData.userInfo.books.push({
          bookId: this.data.book.bookId,
          bookName: this.data.book.bookName
        })
      } else {
        wx.hideLoading()
        wx.showModal({
          title: result.msg
        })
      }
    }
  },
  // 续借
  async handleContinue () {
    await this.goLogin()
    if (!app.globalData.userInfo) {
      return
    } else {
      wx.showLoading({
        title: '续借中...',
        mask: true
      })
      const book = this.data.book
      
      const { result } = await wx.cloud.callFunction({
        name: 'continueBook',
        data: book
      })
      wx.showToast({
        title: result.msg,
        icon: 'success'
      })
    }
  },
  // 归还
  async handleReturn () {
    await this.goLogin()
    if (!app.globalData.userInfo) {
      return
    } else {
      wx.showLoading({
        title: '归还中...',
        mask: true
      })
      const book = this.data.book
      const { result } = await wx.cloud.callFunction({
        name: 'returnBook',
        data: book
      })
      if (result.status === 0) {
        wx.navigateBack({
          delta: 1
        })
        wx.showToast({
          title: result.msg,
          icon: 'success'
        })
        const newUserBooks = app.globalData.userInfo.books.filter(item => item.bookId !== book.bookId)
        app.globalData.userInfo.books = newUserBooks
      } else {
        wx.hideLoading()
      }
    }
  },
  // 显示添加评论
  async handleAddComment (e) {
    await this.goLogin()
    if (!app.globalData.userInfo) {
      return
    } else {
      this.setData({
        isInputting: true
      })
    }
  },
  // 输入界面消失
  handleInputDisappear(e) {
    this.setData({
      isInputting: e.detail.isInputting
    })
  },
  // 更新评论
  handleUpdateComment (e) {
    const data = e.detail
    this.data.comments.push({
      commentId: data.commentId,
      content: data.content
    })
    app.globalData.userInfo.comments.push({
      commentId: data.commentId,
      content: data.content
    })
    this.setData({
      comments: this.data.comments
    })
    this.loadComments(data.noToast)
  }
})
